package com.jd.basic.util;

import com.jd.basic.jwt.JwtUtils;
import com.jd.basic.jwt.LoginData;
import com.jd.basic.jwt.Payload;
import com.jd.basic.jwt.RsaUtils;
import com.jd.user.domain.Logininfo;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

/**
 * 获取登录信息的上下文：把登录的相关信息放到这里面，方便调用
 */

public class LoginContext {
    public static Logininfo getLogininfo(HttpServletRequest request){
        try {
            // 从请求头获取token的值
            String token = request.getHeader("token");
            if (token != null){
                //获取公钥
                PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                //获取载荷 = 数据
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);

                return payload.getLoginData().getLogininfo();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
